<template>
  <div
    class="
      vc-h-full
      vc-overflow-x-hidden
      vc-overflow-y-auto
      vc-w-64
      vc-border-solid
      vc-border-r
      vc-border-gray-300
      vc-select-none
    "
    draggable="false"
  >
    <div class="vc-bg-blue-500 vc-text-white vc-p-2"> 管道 </div>
    <div ref="pipeLegendContainer" class="vc-p-2">
      <div v-for="(el, i) in pipePathLegendData" :key="i" class="vc-cursor-move hover:vc-bg-gray-200">
        <div class="vc-h-12" draggable="true" @dragstart="legendGragstart($event, ConfigurationType.PipePath, i)">
          <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100%" width="100%">
            <template v-if="el.colors && el.type === PipePathType.flat">
              <path
                :d="pipeD"
                :stroke="el.colors[1]"
                style="fill: none"
                stroke-linecap="round"
                stroke-linejoin="round"
                :style="{ 'stroke-width': pipeSize, 'stroke-opacity': el.outerOpacity }"
              />
              <path
                :d="pipeD"
                stroke-dasharray="2, 5"
                :stroke="el.colors[0]"
                style="fill: none"
                :style="{ 'stroke-width': innerPipeSize }"
              />
            </template>
            <template v-else-if="el.type === PipePathType.pipe && el.composeData">
              <path
                v-for="item in el.composeData"
                :key="item.stroke"
                :d="pipeD"
                :stroke="item.stroke"
                stroke-linecap="round"
                stroke-linejoin="round"
                :style="{
                  'stroke-width': item.strokeWidth,
                  fill: 'none',
                }"
              />
            </template>
          </svg>
        </div>
      </div>
    </div>
    <div class="vc-bg-blue-500 vc-text-white vc-p-2"> 流程 </div>
    <div class="vc-flex vc-flex-row vc-flex-wrap vc-items-center vc-pt-2 vc-pl-2">
      <div v-for="(el, i) in flowPathLegendData" :key="i" class="vc-cursor-move vc-hover:bg-gray-200 vc-mb-2 vc-mr-2">
        <div
          :style="{ width: FlowPathLegendSize.width + 'px', height: FlowPathLegendSize.height + 'px' }"
          draggable="true"
          @dragstart="legendGragstart($event, ConfigurationType.FlowPath, i)"
        >
          <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100%" width="100%">
            <FlowPath
              :center-x="FlowPathLegendSize.width / 2"
              :center-y="FlowPathLegendSize.height / 2"
              :init-width="FlowPathLegendSize.width"
              :init-height="FlowPathLegendSize.height"
              :index="i"
              :scale-factor="1"
              :type="el.type"
            />
          </svg>
        </div>
      </div>
    </div>
    <div class="vc-bg-blue-500 vc-text-white vc-p-2"> SVG设备 </div>
    <div class="vc-flex vc-flex-row vc-flex-wrap vc-items-center">
      <div
        v-for="(el, i) in deviceSvgLegendData"
        :key="el.name"
        class="vc-p-0.5 vc-cursor-move vc-rounded-md hover:vc-bg-gray-200"
      >
        <div
          draggable="true"
          @dragstart="legendGragstart($event, ConfigurationType.DeviceSvg, i)"
          @click="showSvgDetail(el)"
        >
          <component :is="el.comp" :width="el.width" />
        </div>
      </div>
    </div>
    <div class="vc-bg-blue-500 vc-text-white vc-p-2"> 图片设备 </div>
    <div class="vc-p-2">
      <div
        v-for="(el, i) in deviceImageLegendData"
        :key="el.src"
        class="vc-w-36 vc-h-36 vc-border vc-border-gray-300 vc-cursor-move"
      >
        <div
          class="vc-w-full vc-h-full"
          draggable="true"
          @dragstart="legendGragstart($event, ConfigurationType.DeviceImage, i)"
        >
          <img :src="el.src" class="vc-w-full" />
        </div>
      </div>
    </div>
    <div class="vc-bg-blue-500 vc-text-white vc-p-2"> 数据点 </div>
    <div class="vc-p-2 vc-flex vc-flex-row vc-flex-wrap vc-items-center">
      <div
        class="vc-border vc-border-solid vc-border-gray-400 vc-p-1 vc-cursor-pointer vc-text-center"
        draggable="true"
        @dragstart="legendGragstart($event, ConfigurationType.LabelValue)"
      >
        <div :style="{ color: LabelColor }">label</div>
        <div>
          <span :style="{ color: ValueColor }" style="margin-right: 3px">value</span>
          <span :style="{ color: UnitColor }">unit</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { defineAsyncComponent, inject, onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
import { SvgDetail, ImgDetail } from "/@/components/Device/resourceDetail";
import { FlowPathType, PipePathType } from "/@/components/types";
import { usePipePath } from "/@/components/PipePath/usePipePath";
import { LabelColor, ValueColor, UnitColor, FlowPathLegendSize } from "/@/components/common";
import { DeviceSvgLegend, RootCommonKey, RootCommon, ConfigurationType } from "./types";
import FlowPath from "/@/components/FlowPath/FlowPath.vue";
import ResizeObserver from "resize-observer-polyfill";
import { getStyle } from "/@/utils/dom";

defineProps<{
  showSvgDetail: (el: DeviceSvgLegend) => void;
}>();

const { pipePathLegendData, deviceImageLegendData, deviceSvgLegendData, flowPathLegendData } = inject(
  RootCommonKey
) as RootCommon;

/**
 * 初始化图例
 */
//管道图例
const {
  innerPipeSize,
  pipeSize,
  d: pipeD,
  updateOptions,
  outerOpacity,
  pipeComposeData,
} = usePipePath({
  containerHeight: 100,
  containerWidth: 100,
  scaleFactor: 1,
});
let resizeObserver: ResizeObserver | null;
const pipeLegendContainer = shallowRef<HTMLDivElement | null>(null);
onMounted(() => {
  if (pipeLegendContainer.value) {
    // const paddingTop = getStyle(pipeLegendContainer.value, "padding-top");
    // console.log(paddingTop);
    resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
      const entry = entries[0];
      if (entry) {
        updateOptions({
          containerWidth: entry.contentRect.width,
          containerHeight: entry.contentRect.height / pipePathLegendData.value.length,
          pipeLength: entry.contentRect.width * 0.8,
          scaleFactor: 1,
        });
      }
    });
    resizeObserver.observe(pipeLegendContainer.value);
  }
  // if (legendItem.value) {
  //   const rect = legendItem.value.getBoundingClientRect();
  //   updateOptions({
  //     containerWidth: rect.width,
  //     containerHeight: rect.height,
  //     pipeLength: rect.width * 0.8,
  //     scaleFactor: 1,
  //   });
  // }
});
onBeforeUnmount(() => {
  if (resizeObserver) {
    console.log("=======>ResizeObserver unmount");
    resizeObserver.disconnect();
    resizeObserver = null;
  }
});
pipePathLegendData.value = [
  { type: PipePathType.flat, colors: ["#ffffff", "#B9C0CC"], outerOpacity },
  { type: PipePathType.pipe, colors: ["#333333"], composeData: pipeComposeData.value },
];
//图片设备图例
const _deviceImageLegendData: { src: string; name: string }[] = [];
for (const key in ImgDetail) {
  _deviceImageLegendData.push({
    src: ImgDetail[key].src as string,
    name: key,
  });
}
deviceImageLegendData.value = _deviceImageLegendData;

const svgKeys: string[] = [];
for (const key in SvgDetail) {
  svgKeys.push(key);
}
//svg设备图例
deviceSvgLegendData.value = svgKeys.map((name) => {
  return {
    name,
    comp: defineAsyncComponent(() => import(`../components/Device/resource/${name}.vue`)),
    width: SvgDetail[name].width * 1.5,
  };
});
//流程图例
flowPathLegendData.value = [
  { type: FlowPathType.Arrow },
  { type: FlowPathType.Diamond },
  { type: FlowPathType.DottedArrow },
  { type: FlowPathType.Triangle },
];

//图例拖拽
function legendGragstart(e: DragEvent, type: ConfigurationType, index?: number) {
  e.dataTransfer?.setData("type", type);
  if (index !== undefined) {
    e.dataTransfer?.setData("index", String(index));
  }
}
</script>
